﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

namespace FastEasyAPI.Module.Swagger;

public static class SwaggerModule
{
    public static void AddSwaggerModule(this IServiceCollection Services)
    {
        Services.AddControllers();
        Services.AddEndpointsApiExplorer();
        Services.AddSwaggerGen(s =>
        {
            //多版本
            typeof(SwaggerVersion).GetEnumNames().ToList().ForEach(v =>
            {
                s.SwaggerDoc(v, new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version = v,
                    Description = $"{v} API",
                    Title = v,
                });
                //添加注释
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                var xmlPath = Path.Combine(basePath, "FastEasy.Readme.xml");
                s.IncludeXmlComments(xmlPath, true);
            });

            s.OperationFilter<AddResponseHeadersFilter>();
            s.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
            s.OperationFilter<SecurityRequirementsOperationFilter>();

            s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Description = "Jwt授权(数据在请求头中进行传输) \n 请输入 Bearer {你的token(无需加括号,Bearer+空格+Token)}",
                Name = "Authorization",
                In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                Type = SecuritySchemeType.ApiKey
            });
        });
    }

    public static void UseSwaggerModule(this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(s =>
        {
            typeof(SwaggerVersion).GetEnumNames().ToList().ForEach(v =>
            {
                s.SwaggerEndpoint($"swagger/{v}/swagger.json", $"{v}");
                s.RoutePrefix = string.Empty;
            });
        });
    }
}